package com.hx.zhg.util;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理文章html内容
 */
public class HtmlUtil {
	private static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	private static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>";    // 定义style的正则表达式
	private static final String REGEX_HTML = "<[^>]+>"; 							  // 定义HTML标签的正则表达式
	private static final String REGEX_lINE_TAG = "<br>|<br/>|</p>"; 				  // 定义HTML换行标签
	private static final String REGEX_MULTI_SPACE = "[\\s\\p{Zs}]+"; 				  // 定义4个以上的空格
	private static final String REGEX_NBSP_SPACE = "(&nbsp;)+"; 				 	  // 定义&nbsp;
	// private static final String REGEX_SPACE = "\\s*|\t|\r|\n"; 					  // 定义空格回车换行符

	/**
	 * @Description: 删除html标签。替换回车换行符为\t
	 * @data: 2014年9月20日
	 * @author：shikebing
	 * @param htmlStr
	 * @return
	 */
	public static String delHTMLTag(String htmlStr) {

		if (StringUtils.isEmpty(htmlStr)) {
			return "";
		}

		// 过滤换行标签为四个空格，不能是\t
		Pattern p_line_tag = Pattern.compile(REGEX_lINE_TAG,
				Pattern.CASE_INSENSITIVE);
		Matcher m_line_tag = p_line_tag.matcher(htmlStr);
		htmlStr = m_line_tag.replaceAll("    ");

		// 过滤script标签
		Pattern p_script = Pattern.compile(REGEX_SCRIPT,
				Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll("");

		// 过滤style标签
		Pattern p_style = Pattern
				.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll("");

		// 过滤html标签
		Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll("");

		// 过滤多个空格（4个以上），替换成制表符
		Pattern p_multi_space = Pattern.compile(REGEX_MULTI_SPACE, Pattern.CASE_INSENSITIVE);
		Matcher m_multi_space = p_multi_space.matcher(htmlStr);
		htmlStr = m_multi_space.replaceAll("\t");
		
		// 过滤nbsp
		Pattern p_nbsp = Pattern.compile(REGEX_NBSP_SPACE, Pattern.CASE_INSENSITIVE);
		Matcher m_nbsp = p_nbsp.matcher(htmlStr);
		htmlStr = m_nbsp.replaceAll("");
		
		return htmlStr;
	}
}
